﻿using FairyGUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using WgFrame.Net;

public class ChangeHeroPanel : BasePopupPanel
{
    /// <summary>
    /// 将要上阵位置 大于0 换
    /// </summary>
    private byte zhenPos;
    private GList lsHeros;
    private bool isShangZhening;

    public override void Init()
    {
        base.Init();

        frame = view.GetChild("n1").asCom;
        lsHeros = frame.GetChild("n1").asList;
        lsHeros.onClickItem.Add(OnSelectHeroClick);
    }

    public override void Show(params object[] para)
    {
        zhenPos = (byte)para[0];
        List<Hero> heroes = (List<Hero>)para[1];
        MsgListenerMgr.AddMsgListener(MsgListenerType.ShangZhen, OnShangZhenMsg);

        isShangZhening = false;
        this.SetInfo(heroes);

        base.Show(para);
    }

    public override void Close()
    {
        MsgListenerMgr.RemoveMsgListener(MsgListenerType.ShangZhen, OnShangZhenMsg);
        base.Close();
    }

    protected override GComponent CreateView()
    {
        return UIPackage.CreateObject("Main", "panel_shangzhen1").asCom;
    }

    private void SetInfo(List<Hero> heroes)
    {
        lsHeros.RemoveChildrenToPool();
        for (int i=0; i<heroes.Count; i++)
        {
            Hero hero = heroes[i];
            GButton button = lsHeros.AddItemFromPool().asButton;
            button.data = hero.id;
            GTextField tfName = button.GetChild("n3").asTextField;
            tfName.text = string.Format("{0}+{1}", hero.GetName(), hero.JinJieLevel);
            tfName.color = hero.InitHero == null ? tfName.color = CommonUtil.White : CommonUtil.GetHeroPinZhiColor(hero.InitHero.quality);

            GTextField tfDujie = button.GetChild("n4").asTextField;
            tfDujie.text = CommonUtil.GetDuJieName(hero.DuJieLevel);
            tfDujie.color = CommonUtil.GetHeroDuJieColor(hero.DuJieLevel);
        }
    }

    private void OnSelectHeroClick(EventContext context)
    {
        if (lsHeros.selectedIndex  < 0)
        {
            return;
        }
        if (isShangZhening)
        {
            return;
        }

        GButton button = lsHeros.GetChildAt(lsHeros.selectedIndex).asButton;
        long id = (long)button.data;
        RequestHelper.SendShangZhenRequest(id, zhenPos);
        isShangZhening = true;
    }

    private void OnShangZhenMsg(params object[] para)
    {
        Close();
    }
}
